package com.photoeditor.demo.ad;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;

import com.billing.base.svip.SVipManager;
import com.common.base.ComponentContext;
import com.common.base.log.RLog;
import com.common.base.utils.DebugUtil;
import com.common.base.utils.ProcessUtils;
import com.common.base.utils.TimeConstant;
import com.common.base.utils.TimeUtils;
import com.common.commercialize.ad.AdDisplay;
import com.common.commercialize.ad.AdManager;
import com.common.commercialize.channel.BuyUserManager;
import com.common.commercialize.sdk.CommercializeSDK;
import com.common.commercialize.utils.TaskRunnable;
import com.common.statistics.StatisticsUtils;
import com.photoeditor.R;
import com.photoeditor.demo.model.preference.SpUtils;
import com.photoeditor.demo.model.subscribe.manager.AppVipManager;
import com.photoeditor.demo.statistics.StatisticsConstant;
import com.wv.nw.activity.AdActivity;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import static com.photoeditor.demo.ad.AdProvider.REASON_AD_OBJECT_ERROR;
import static com.photoeditor.demo.ad.AdProvider.REASON_LOCAL_SHOW_COUNT_LIMIT;
import static com.photoeditor.demo.ad.AdProvider.REASON_LOCAL_SHOW_TIME_INTERVAL_LIMIT;
import static com.photoeditor.demo.ad.AdProvider.REASON_SVIP_USER;
import static com.photoeditor.demo.ad.AdProvider.REASON_UNIT_ID_ERROR;


/**
 * Created by dell on 2017/12/27.
 */

public class FullScreenAdProvider {
    private static final String TAG = "FullScreen";
    /**
     * 所有全屏广告一天弹的次数
     */
    private static final String KEY_ALL_AD_SHOW_AD_COUNT = "ALL_AD_SHOW_AD_COUNT";

    /**
     * 所有全屏广告上一次弹的时间
     */
    private static final String KEY_ALL_AD_DAILY_SHOW_AD_PREV_TIME = "ALL_AD_DAILY_SHOW_AD_PREV_TIME";

    /**
     * 单个广告一天弹的次数
     */
    private final String KEY_AD_SHOW_AD_COUNT = "AD_SHOW_AD_COUNT";

    /**
     * 单个广告上一次弹的时间
     */
    private final String KEY_AD_DAILY_SHOW_AD_PREV_TIME = "AD_DAILY_SHOW_AD_PREV_TIME";


    private int mMaxAdDayCount = -1;

    private final AdProvider mAdProvider;
    private String mSceneName;
    private String mUnitId;
    private int mFunId;
    private TaskRunnable mShowAdFollowupActionRunnable;
    private int mSceneShowAdCount;
    private final boolean DEBUG = DebugUtil.isDebuggable() || CommercializeSDK.TestUser.isTestUser();
    private boolean mAdLoading = false;

    private boolean mAdShowing = false;

    private boolean mRequestNoStrategy = true;
    private String mImpressionEntrance;

    private Map<String, Object> mAdValues = new HashMap<>();


    private Class mFakeFullScreenActivityClass = AdActivity.class;
    private int mFakeFullScreenLayoutId = R.layout.commercialize_ad_style_2;

    public FullScreenAdProvider(String sceneName, String unitId, int funId) {
        mSceneName = sceneName;
        mUnitId = unitId;
        mFunId = funId;
        mAdProvider = AdProvider.newProvider(mSceneName, mUnitId, mFunId);
        mAdProvider.setAdType(AdProvider.AdType.Interstitial);
    }

    public void addStatisticsInfo(String... info) {
        mAdProvider.addStatisticsInfo(info);
    }

    public void setStatisticsInfo(String... info) {
        mAdProvider.setStatisticsInfo(info);
    }

    /**
     * 没有策略时是否加载广告，默认加载
     *
     * @param requestNoStrategy
     */
    public void setRequestNoStrategy(boolean requestNoStrategy) {
        mRequestNoStrategy = requestNoStrategy;
    }

    public void setMaxAdDayCount(int maxAdDayCount) {
        mMaxAdDayCount = maxAdDayCount;
    }

    public boolean needRequest(int unitIdIndex) {
        if (AppVipManager.isVip()) {
            statisticsNoRequestAd(REASON_SVIP_USER);
            return false;
        }

        //没有取到策略 按原逻辑
        final SpUtils sp = SpUtils.obtain();
        final long currentTimeMillis = System.currentTimeMillis();
        long lastShowAdTime = sp.getLong(KEY_AD_DAILY_SHOW_AD_PREV_TIME + mSceneName, 0);
        if (lastShowAdTime == 0) {
            // 第一次进来
            mSceneShowAdCount = 0;
            if (DEBUG) {
                RLog.d(TAG, "first show " + mSceneName);
            }
        } else if (!TimeUtils.isSameDayOfMillis(currentTimeMillis, lastShowAdTime)) {
            // 过了一天
            sp.save(KEY_AD_SHOW_AD_COUNT + mSceneName, 0);
            mSceneShowAdCount = 0;
            if (DEBUG) {
                RLog.d(TAG, "new day for " + mSceneName);
            }
        } else {
            mSceneShowAdCount = sp.getInt(KEY_AD_SHOW_AD_COUNT + mSceneName, 0);
            if (DEBUG) {
                RLog.d(TAG, mSceneName + " already show ad times:" + mSceneShowAdCount);
            }
        }
        // 当天达到最大次数则不请求
        if (mMaxAdDayCount != -1 && mSceneShowAdCount >= mMaxAdDayCount) {
            if (DEBUG) {
                RLog.d(TAG, "the maximum number of times for " + mSceneName);
            }
            statisticsNoRequestAd(REASON_LOCAL_SHOW_COUNT_LIMIT);
            return false;
        }

        return true;
    }


    public void statisticsNoRequestAd(String reason) {
        mAdProvider.statisticsNoRequestAd(reason);
    }

    public void statisticsNoShowAd(String reason) {
        mAdProvider.statisticsNoShowAd(reason);
    }

    public void loadAd(Activity activity) {
        if (mAdProvider.hasAd()) {
            if (DEBUG) {
                RLog.d(TAG, "has ad");
            }
            return;
        }
        if (TextUtils.isEmpty(mUnitId)) {
            statisticsNoRequestAd(REASON_UNIT_ID_ERROR);
            return;
        }
        if (mAdLoading) {
            if (DEBUG) {
                RLog.d(TAG, "ad loading...");
            }
            return;
        }
        mAdLoading = true;

        final AdManager.AdRequest adRequest = new AdManager.AdRequest();
        adRequest.setSceneName(mSceneName)
                .addAllByDefault(activity);//TODO:正式包需改为只支持全屏
        mAdProvider.setOnAdListener(adListener);
        mAdProvider.loadAd(adRequest);
    }

    public void setFakeFullScreenActivityClass(Class fakeFullScreenActivityClass) {
        mFakeFullScreenActivityClass = fakeFullScreenActivityClass;
    }

    public void setFakeFullScreenLayoutId(int fakeFullScreenLayoutId) {
        mFakeFullScreenLayoutId = fakeFullScreenLayoutId;
    }

    public void putAdExtra(String key, Object values) {
        mAdValues.put(key, values);
    }

    public boolean showAd(TaskRunnable runnable, String entrance) {
        if (AppVipManager.isVip()) {
            statisticsNoShowAd(REASON_SVIP_USER);
            return false;
        }
        int intervalMin = 1;
        SpUtils sp = SpUtils.obtain();
        long currentTimeMillis = System.currentTimeMillis();
        long prevShowAdTime = sp.getLong(KEY_ALL_AD_DAILY_SHOW_AD_PREV_TIME, 0); //这里使用所有广告的上次展示时间，防止短时间内多次展示全屏广告
        if (currentTimeMillis - prevShowAdTime < TimeConstant.ONE_MIN * intervalMin) {
            // 一分钟不请求和展示
            if (DEBUG) {
                RLog.d(TAG, mSceneName + " show ad but " + intervalMin + " min interval...");
            }
            statisticsNoShowAd(REASON_LOCAL_SHOW_TIME_INTERVAL_LIMIT);
            return false;
        }

        boolean isAdValid = true;
        String adCacheKey = "";
        if (!mAdProvider.hasAd()) {
            isAdValid = false;
        } else {
            adCacheKey = mAdProvider.getAdCacheKey();
            if (!AdManager.getInstance().hasAd(adCacheKey)) {
                isAdValid = false;
            }
        }

        if (!isAdValid) {
            statisticsNoShowAd(AdProvider.REASON_NO_VALID_AD);
            return false;
        }

        boolean ret = false;
        Object ad = AdManager.getInstance().getAd(adCacheKey);
        if (ad != null) {
            if (DEBUG) {
                RLog.d(TAG, mSceneName + " show ad");
            }

            mAdProvider.setOnAdListener(adListener);//设置广告，防止前个广告释放了监听导致回调不执行

            mShowAdFollowupActionRunnable = runnable;
            mImpressionEntrance = entrance;
            AdDisplay.Builder builder = new AdDisplay.Builder(ComponentContext.getContext(), mFakeFullScreenActivityClass);

            Intent intent = builder.getIntent();
            Set<String> strings = mAdValues.keySet();
            for (String key : strings) {
                Object values = mAdValues.get(key);
                if (values instanceof Integer) {
                    intent.putExtra(key, (Integer) values);
                } else {
                    intent.putExtra(key, String.valueOf(values));
                }
            }
            mAdValues.clear();

            builder.setKey(adCacheKey)
                    .setLayoutId(mFakeFullScreenLayoutId)
                    .setDefaultResId(R.drawable.ic_default_image);
//            if (mFakeFullScreenLayoutId == R.layout.commercialize_ad_style_5) {
//                builder.setIfNeedLimitHeight(true)
//                        .setAdCoverMaxHeight(DeviceUtils.dip2px(200f));
//            }
            ret = builder.show(ad);
            if (!ret) {
                statisticsNoShowAd(REASON_AD_OBJECT_ERROR);
                mShowAdFollowupActionRunnable = null;
                mImpressionEntrance = null;
            } else {
                mAdShowing = true;
                sp.save(KEY_AD_SHOW_AD_COUNT + mSceneName, mSceneShowAdCount + 1);
                sp.save(KEY_AD_DAILY_SHOW_AD_PREV_TIME + mSceneName, currentTimeMillis);

                int allAdDayCount = sp.getInt(KEY_ALL_AD_SHOW_AD_COUNT);
                if (TimeUtils.isSameDayOfMillis(prevShowAdTime, currentTimeMillis)) {
                    sp.save(KEY_ALL_AD_SHOW_AD_COUNT, allAdDayCount + 1);
                } else {
                    sp.save(KEY_ALL_AD_SHOW_AD_COUNT, 1);
                }
                sp.save(KEY_ALL_AD_DAILY_SHOW_AD_PREV_TIME, currentTimeMillis);
            }
        }
        return ret;
    }

    private void checkShowSVip(int time) {
//        if (AppVipManager.isVip()) {
//            return;
//        }

//        if (System.currentTimeMillis() - AppApplication.getInstallTime() < TimeConstant.ONE_DAY * 3
//                && SVipController.getInstance().canShowSVipActivityAutoToday() && (time == 2 || time == 4 || time == 8)) {
//            SVipController.getInstance().showPurchaseActivityOfNoAd();
//        }
    }

    public void destroyAd() {
        if (mAdShowing) {
            return;
        }

        mAdLoading = false;
        mAdProvider.destroy();
    }

    public static void statistics(String eventSuffix, String... attributes) {
        if (ProcessUtils.isMainProcess(ComponentContext.getContext())) {
            StatisticsUtils.statisics(StatisticsConstant.UMENG_CUSTOM_EVENT_PREFIX_FUNCTION, eventSuffix, attributes);
        }
    }

    private AdProvider.OnAdListener adListener = new AdProvider.OnAdListener() {

        @Override
        public void onAdLoadFinish(String cacheKey) {
            mAdLoading = false;
            super.onAdLoadFinish(cacheKey);
        }

        @Override
        public void onAdLoadFailure(String err) {
            mAdLoading = false;
            super.onAdLoadFailure(err);
        }

        @Override
        public void onAdClosed(String cacheKey) {
            mAdShowing = false;

            if (mShowAdFollowupActionRunnable != null) {
                mShowAdFollowupActionRunnable.runSelfAdaptation();
                mShowAdFollowupActionRunnable = null;
            }
            checkShowSVip(SpUtils.obtain().getInt(KEY_ALL_AD_SHOW_AD_COUNT));

            destroyAd();
            super.onAdClosed(cacheKey);
        }

        @Override
        public void onAdImpression(String cacheKey) {
            super.onAdImpression(cacheKey);

            String entrance = TextUtils.isEmpty(mImpressionEntrance) ? "unknown" : mImpressionEntrance;
            StatisticsUtils.statisics(StatisticsConstant.UMENG_CUSTOM_EVENT_PREFIX_FUNCTION, "interstitial", "entrance", entrance, "usertype", String.valueOf(BuyUserManager.getInstance().isBuyUser()));
        }
    };
}
